import os
import random
import sys
import time

import numpy as np
import torch

import felix_flags
import utils
import logging
from logging import handlers

#from transformers import Trainer
from transformers import BertPreTrainedModel
#sys.path.append('/evafs/angzhao/transformers-master20201027_forzhaoang/src')
#pip install transformers==4.33.0
import tokenization
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm, trange
from transformers import get_linear_schedule_with_warmup
from torch.optim import AdamW
from seqeval.metrics import f1_score, classification_report
from metric import compute_metrics_with_fuse
from mate_data_loader import MateIterableDataset, collate_fn
from modeling_mate import MateModel, BertConfig
from datetime import datetime

MODEL_CLASSES = {
    'bert_tagging': (BertConfig, MateModel)
}

today = datetime.now().strftime(f'%Y%m%d_%H%M%S')
logger = logging.getLogger('__log__')


def get_point_score(golden_tags, pred_tags, masks, tokens):
    ttag = 0
    ftag = 0
    for i, golden_tag in enumerate(golden_tags):
        pred_tag = pred_tags[i]
        mask_i = masks[i]
        for j, v in enumerate(golden_tag):
            if mask_i[j] == 0: continue
            if golden_tag[j] == pred_tag[j]:
                ttag += 1
            else:
                ftag += 1
    acc = ttag / (ttag + ftag)

    return f'{acc:.4}'

def set_seed(args):
    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    if args.n_gpu > 0:
        torch.cuda.manual_seed_all(args.seed)

def save_checkpoint(args, model, output_dir):
    logger.info("Before Saving model checkpoint to %s", output_dir)
    model_to_save = model.module if hasattr(model, 'module') else model  # Take care of distributed/parallel training
    model_to_save.save_pretrained(output_dir)
    torch.save(args, os.path.join(output_dir, 'training_args.bin'))
    args_writer = open(os.path.join(output_dir, 'training_args.txt'), 'w', encoding='utf-8')
    print(f'{args}', file=args_writer)

    logger.info("Saving model checkpoint to %s", output_dir)


def save_pred_result(save_filename, line_tokens, masks, preds, pred_probs=None, golds=None):
    assert len(line_tokens) == len(masks)
    assert len(line_tokens) == len(preds)
    if golds is not None:
        assert len(line_tokens) == len(golds)
    save_file = open(save_filename, 'w', encoding='utf-8')
    for i, v in enumerate(line_tokens):
        tokens = v
        items = list()
        for j, w in enumerate(v):
            if masks[i][j] == 0:
                break
            if golds is not None:
                items.append(f"{tokens[j]}/{golds[i][j]}/{preds[i][j]}")
            else:
                items.append(f'{tokens[j]}/{preds[i][j]}')
        sent = ' '.join(items[1:-1])
        save_file.write(f"{sent}\n")
    save_file.close()


def train(args, model, taskdir):
    if args.local_rank in [-1, 0]:
        tb_writer = SummaryWriter()

    message = f'*****running training*****\n' \
              f'ngpu = {args.n_gpu}\n  local rank = {args.local_rank} save_steps= {args.save_steps}\n' \
              f'init = {args.init_checkpoint}\n' \
              f'num epoch {args.num_train_epochs}\n' \
              f'batch size per gpu {args.per_gpu_train_batch_size}\n' \
              f'gradient accumulation steps {args.gradient_accumulation_steps}\n' \
              f'lr {args.learning_rate}\n' \
              f'train_file {args.train_file}\n' \
              f'Note {args.note}\n'

    train_dataset = MateIterableDataset(datadir=args.train_file, args=args)
    args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
    train_dataloader = DataLoader(train_dataset,  batch_size=args.train_batch_size, collate_fn=collate_fn, num_workers=args.worker,  drop_last=True)

    t_total = len(train_dataset) // args.gradient_accumulation_steps * args.num_train_epochs // args.train_batch_size

    total_bs = args.train_batch_size * args.gradient_accumulation_steps * (
        torch.distributed.get_world_size() if args.local_rank != -1 else 1)
    message += f'num examples {len(train_dataset)}\n' \
              f'total train batch size(w. parallel, distributed & accumulation) {total_bs}\n' \
              f'total optimization steps {t_total}\n'
    logger.info(message)

    no_decay = ['bias', 'LayerNorm.weight']
    optimizer_grouped_parameters = [
        {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
         'weight_decay': args.weight_decay},
        {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
    ]
    optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
    # optimizer = torch.optim.Adam(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon, amsgrad=True)
    # scheduler = ReduceLROnPlateau(optimizer, mode='max', factor=0.5, patience=3, verbose=1, epsilon=1e-4, cooldown=0, min_lr=0, eps=1e-8)
    scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps,
                                                num_training_steps=t_total)
    if args.fp16:
        try:
            from apex import amp
        except ImportError:
            raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.")
        model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level)

    # multi-gpu training (should be after apex fp16 initialization)
    if args.n_gpu > 1:
        model = torch.nn.DataParallel(model)

    # Distributed training (should be after apex fp16 initialization)
    if args.local_rank != -1:
        model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
                                                          output_device=args.local_rank,
                                                          find_unused_parameters=True)

    global_step = 0
    tr_loss, logging_loss = 0.0, 0.0
    best_fuse_f1 = 0
    best_ep = 0
    model.zero_grad()
    train_iter = trange(args.num_train_epochs, desc='Epoch', disable=args.local_rank not in [-1, 0])
    for epoch_idx in train_iter:
        epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0])
        for step, batch in enumerate(epoch_iterator):
            model.train()
            batch = tuple(t.to(args.device) for t in batch)
            inputs = {  'input_ids': batch[0],
                        'attention_mask': batch[1],
                        'token_type_ids': batch[2],
                        'mlm_label_ids':batch[3],
                        'edit_tag_ids': batch[4],
                        'edit_pointing': batch[5],
                        'is_training': True,
                      }
            
            outputs = model(**inputs)
            # loss, tag_logits, tag_loss, tag_acc, pointing_logits, point_loss, point_acc, mlm_idx, mlm_loss, mlm_acc
            if len(outputs) == 10:
                loss = outputs[0]
                mlm_loss = outputs[2]
                mlm_acc = outputs[3]
                edit_tag_loss = outputs[5]
                edit_tag_acc = outputs[6]
                edit_point_loss = outputs[8]
                edit_point_acc = outputs[9]

                if args.n_gpu > 1:
                    loss = loss.mean()
                    edit_tag_loss = edit_tag_loss.mean()
                    edit_tag_acc = edit_tag_acc.mean()
                    edit_point_loss = edit_point_loss.mean()
                    edit_point_acc = edit_point_acc.mean()
                    mlm_loss = mlm_loss.mean()
                    mlm_acc = mlm_acc.mean()

                log_str = f'loss {loss:.5}, tag_loss {edit_tag_loss:.5}, tag_acc {edit_tag_acc:.5}, ' \
                          f'point_loss {edit_point_loss:.5}, point_acc {edit_point_acc:.5}, ' \
                          f'mlm_loss {mlm_loss:.5}, mlm_acc {mlm_acc:.5}'

            elif len(outputs) == 3:
                # n_gpu == 1
                loss = outputs[0]
                logits = outputs[1]
                acc = outputs[2]
                log_str = f'loss {loss:.5},  acc {acc:.5}, '

            if args.n_gpu > 1:
                loss = loss.mean()  # mean() to average on multi-gpu parallel training
                # loss = torch.abs((loss - b)) + b
            else:
                pass

            if args.gradient_accumulation_steps > 1:
                loss = loss / args.gradient_accumulation_steps

            if args.fp16:
                with amp.scale_loss(loss, optimizer) as scaled_loss:
                    scaled_loss.backward()
                torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
            else:
                loss.backward()
                torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)

            tr_loss += loss.item()
            if (step + 1) % args.gradient_accumulation_steps == 0:
                optimizer.step()
                scheduler.step()  # Update learning rate schedule
                model.zero_grad()
                global_step += 1

                if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
                    # Log metrics
                    tb_writer.add_scalar('lr', scheduler.get_lr()[0], global_step)
                    tb_writer.add_scalar('loss', (tr_loss - logging_loss) / args.logging_steps, global_step)
                    logging_loss = tr_loss
                    logger.info(f'{log_str} lr {scheduler.get_lr()[0]:.5}')
                    torch.cuda.empty_cache()

                #logger.info(f'save checkpoint at {global_step} every {args.save_steps}')
                if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0:
                    # Save model checkpoint every save steps
                    output_dir = os.path.join(taskdir, f'checkpoint-epoch-{epoch_idx}-steps-{global_step}')
                    if not os.path.exists(output_dir):
                        os.makedirs(output_dir)
                    logger.info(f'save checkpoint to {output_dir}')
                    save_checkpoint(args, model, output_dir)

                if args.max_steps > 0 and global_step > args.max_steps:
                    epoch_iterator.close()
                    break
        if args.local_rank in [-1, 0]:
            output_dir = os.path.join(taskdir, f'checkpoint-epoch-{epoch_idx}-end')
            if args.evaluate_during_training:  # Only evaluate when single GPU otherwise metrics may not average well
                fuse_f1 = evaluate(args, model, )
                tb_writer.add_scalar('eval_f1', fuse_f1, global_step)
                if fuse_f1 > best_fuse_f1:
                    logger.info(f'f1 update epoch {epoch_idx} fuse_f1: {best_fuse_f1} -> {fuse_f1}')
                    best_fuse_f1 = fuse_f1
                    best_ep = epoch_idx
                    save_checkpoint(args, model, output_dir)
                else:
                    logger.info(f'f1 not updated {epoch_idx} fuse_f1: {fuse_f1}; best: {best_fuse_f1} epoch: {best_ep}')
            else:
                save_checkpoint(args, model, output_dir)

        if args.max_steps > 0 and global_step > args.max_steps:
            train_iter.close()
            break

    if args.local_rank in [-1, 0]:
        tb_writer.close()

    return global_step, tr_loss / global_step


def model_predict(model, inputs):
    with torch.no_grad():
        outputs = model(**inputs)
    return outputs

#ignore.
def evaluate(args, model, ):
    # eval single tagging or insertion
    eval_output_dir = args.output_dir
    if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]:
        os.makedirs(eval_output_dir)
    label_map = utils.read_label_map(args.label_map_file)
    label_map_rev = {v: k for k, v in label_map.items()}
    eval_dataset = MateIterableDataset(args, args.dev_file)

    args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
    # Note that DistributedSampler samples randomly
    eval_dataloader = DataLoader(eval_dataset, batch_size=args.eval_batch_size, collate_fn=collate_fn, num_workers=args.work,  drop_last=True, )
    tokenizer = tokenization.FullTokenizer(args.vocab_file)
    # Eval!
    logger.info("***** Running evaluation *****")
    logger.info("  Num examples = %d", len(eval_dataset))
    logger.info("  Batch size = %d", args.eval_batch_size)
    nb_eval_steps = 0

    edit_tag_pred = []
    edit_point_pred = []
    edit_point_gold = []
    edit_tag_gold = []

    mlm_label_pred = []
    mlm_label_gold = []
    masks = []
    tok_ids = []
    t0 = time.time()
    model.eval()
    batches = 0
    for batch in tqdm(eval_dataloader, desc="Evaluating"):
        batches += 1

        batch = tuple(t.to(args.device) for t in batch)
        if args.task == 'tagging':
            inputs = {'input_ids': batch[0],
                      'attention_mask': batch[1],
                      'token_type_ids': batch[2],
                      'is_training': False
                      }
        elif args.task == 'insertion':
            inputs = {'input_ids': batch[0],
                      'attention_mask': batch[1],
                      'token_type_ids': batch[2],
                      'masked_lm_positions': batch[3],
                      }

        with torch.no_grad():
            outputs = model(**inputs)
            #loss, tag_act_idx, tag_loss, tag_acc, pointing_act_idx, point_loss, point_acc, mlm_act_idx, masked_lm_loss, mlm_acc

        if len(outputs) == 10:
            mlm_act_idx = outputs[1]
            tag_act_idx = outputs[4]
            pointing_act_idx = outputs[7]

        elif len(outputs) == 3:
            loss = outputs[0]
            logits = outputs[1]
            acc = outputs[2]
            log_str = f'loss {loss:.5},  acc {acc:.5}, '

        nb_eval_steps += 1

        if args.task == 'tagging':
            ba_tok_ids = batch[0].detach().cpu().numpy().tolist()
            ba_mask = batch[1].detach().cpu().numpy().tolist()

            ba_mlmpred = mlm_act_idx.detach().cpu().numpy().tolist()
            ba_mlmgold = batch[3].detach().cpu().numpy().tolist()

            ba_tagpred = tag_act_idx.detach().cpu().numpy().tolist()
            ba_taggold = batch[4].detach().cpu().numpy().tolist()

            ba_pointpred = pointing_act_idx.detach().cpu().numpy().tolist()
            ba_pointgold = batch[5].detach().cpu().numpy().tolist()

            mlm_label_pred.extend(ba_mlmpred)
            mlm_label_gold.extend(ba_mlmgold)

            edit_tag_pred.extend(ba_tagpred)
            edit_tag_gold.extend(ba_taggold)

            edit_point_pred.extend(ba_pointpred)
            edit_point_gold.extend(ba_pointgold)

            masks.extend(ba_mask)
            tok_ids.extend(ba_tok_ids)

        elif args.task == 'insertion':
            # todo
            pass

    t1 = time.time()
    bss = batches / (t1 - t0)
    logger.info(f'finished predict, timecost {t1 - t0:.4}, batches/sec {bss:.4} \nckpt:{args.init_checkpoint}')
    tokens = [tokenizer.convert_ids_to_tokens(indices) for indices in tok_ids]
    # sequence labeling
    golden_edit_tags = [['S-' + label_map_rev[v] for j, v in enumerate(arr) if masks[i][j] == 1] for i, arr in
                        enumerate(edit_tag_gold)]
    predicted_edit_tags = [['S-' + label_map_rev[v] for j, v in enumerate(arr) if masks[i][j] == 1] for i, arr in
                           enumerate(edit_tag_pred)]
    tokens = [[v for j, v in enumerate(arr) if masks[i][j] == 1] for i, arr in enumerate(tokens)]

    sl_report = classification_report(golden_edit_tags, predicted_edit_tags, digits=4)
    sl_fuse_report, fuse_f1 = compute_metrics_with_fuse(golden_edit_tags, predicted_edit_tags)
    logger.info(f'\n{sl_report}\n{sl_fuse_report}')
    # pointer metrics
    point_acc = get_point_score(edit_point_gold, edit_tag_pred, masks, tokens)
    logger.info(f'Point_ACC :{point_acc}')

    mlm_acc = get_point_score(mlm_label_gold, mlm_label_pred, mlm_label_gold, tokens=None)
    logger.info(f'Point_ACC :{mlm_acc}')

    output_eval_file = os.path.join(eval_output_dir, os.path.basename(args.dev_file) + '.result')
    t2 = time.time()
    logger.info(f'finished compute_metrics, timecost {t2 - t0:.4} save result to {output_eval_file}')
    save_pred_result(output_eval_file, tokens, masks, edit_tag_pred, pred_probs=None, golds=edit_tag_gold)

    return fuse_f1


def main():
    args = felix_flags.config_opts()
    taskdir = os.path.join(args.output_dir, args.task + '_' + today)
    if not os.path.exists(taskdir):
        os.makedirs(taskdir)
    format_str = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s: %(message)s')
    logger.setLevel(logging.INFO)
    sh = logging.StreamHandler()
    th = handlers.TimedRotatingFileHandler(filename=os.path.join(taskdir, '_log_.log'),
                                           when='D',
                                           backupCount=0,
                                           encoding='utf-8')
    sh.setFormatter(format_str)
    th.setFormatter(format_str)
    logger.addHandler(sh)
    logger.addHandler(th)
    logger.info(f'taskdir {taskdir}')
    if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train and not args.overwrite:
        raise ValueError(
            f"Output directory ({args.output_dir}) already exists and is not empty. Use --overwrite or rename.")

    if args.server_ip and args.server_port:
        import ptvsd
        print("Waiting for debugger attach")
        ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
        ptvsd.wait_for_attach()

    if args.local_rank == -1 or args.no_cuda:
        device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
        args.n_gpu = torch.cuda.device_count()
    else:  # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
        torch.cuda.set_device(args.local_rank)
        device = torch.device("cuda", args.local_rank)
        torch.distributed.init_process_group(backend='nccl')
        args.n_gpu = 1
    args.device = device
    logger.info(
        f'Process rank:{args.local_rank}, device:{device}, n_gpu:{args.n_gpu}, dist training:{bool(args.local_rank != -1)}, 16-bits:{args.fp16}')
    set_seed(args)
    logger.info("Training/evaluation parameters %s", args)

    if args.local_rank not in [-1, 0]:
        torch.distributed.barrier()
    label_map = utils.read_label_map(args.label_map_file)

    args.model_type = args.model_type.lower()
    assert (args.task == 'tagging' and args.model_type.find('tagging') > -1 and args.config_name.find(
        'tagging') > -1) or \
           (args.task == 'insertion' and args.model_type.find('insertion') > -1 and args.config_name.find(
               'insertion') > -1), 'task and model mismatch'

    config_class, model_class = MODEL_CLASSES[args.model_type]
    config = config_class.from_pretrained(args.config_name)

    if args.task == 'tagging':
        config.num_labels = len(label_map)
    
    if args.init_checkpoint != 'None':
        ckpt = os.path.join(args.resource_dir, args.init_checkpoint)
        if  os.path.exists(ckpt):
            logger.info(f'reset ckpt {args.init_checkpoint} to {ckpt} ')
            args.init_checkpoint = ckpt
        model = model_class.from_pretrained(args.init_checkpoint, config=config)
        logger.info(f'ckpt loaded {args.init_checkpoint} done.')
    else:
        logger.info('init ckpt is None, cold start.')
        model = model_class(config=config)
        if args.do_train is False and args.do_eval is True:
            logger.warn('init ckpt is None, please check!')
            raise
    
    if args.local_rank == 0:
        torch.distributed.barrier()

    if args.do_train:
        model.to(args.device)
        train(args, model, taskdir)

        if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0] and \
                (args.local_rank == -1 or torch.distributed.get_rank() == 0):
            os.makedirs(args.output_dir)

        logger.info("Saving model checkpoint to %s", args.output_dir)
        # Save a trained model, configuration and tokenizer using `save_pretrained()`.
        # They can then be reloaded using `from_pretrained()`
        model_to_save = model.module if hasattr(model,
                                                'module') else model  # Take care of distributed/parallel training
        model_to_save.save_pretrained(args.output_dir, safe_serialization=False)
        # Good practice: save your training arguments together with the trained model
        torch.save(args, os.path.join(args.output_dir, 'training_args.bin'))

    if args.do_eval and args.local_rank in [-1, 0]:
        # model = model_class.from_pretrained(args.init_checkpoint, config=config)
        model.to(args.device)
        evaluate(args, model)

    # repeat
    logger.info("Training/evaluation parameters %s", args)

#pip install jieba  transformers==4.39.1 torch==2.3.0+cu121 numpy six tensorboard seqeval ltp
if __name__ == "__main__":
    main()
    #CUDA_VISIBLE_DEVICES=0 python  run_task_mate_pretrain.py --do_train  --train_file D:/workspace/res_input_output/raw_input_bak/ --save_steps=100000

    #CUDA_VISIBLE_DEVICES=0 python  run_task_mate_pretrain.py --do_train  --init_checkpoint /home/jovyan/work/on/resource/chinese-bert-wwm-ext/pytorch_model.bin --train_file /home/jovyan/work/on/raw_input_bak --save_steps=100000 --resource_dir  /home/jovyan/work/on/resource